using AutoMapper;
using B.S.NewMedical.Api.Read.Application.Command.MobileService.Consult;
using B.S.NewMedical.Api.Read.DTOS.Consult;
using B.S.NewMedical.Domain.MobileService;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Read.Application.Handler.MobileService.Consult
{
    /// <summary>
    /// 获取健康咨询问题列表处理器
    /// </summary>
    public class GetConsultQuestionsHandler : IRequestHandler<GetConsultQuestionsCommand, ApiResult<PagedList<ConsultQuestionDto>>>
    {
        private readonly IBaseRepository<ConsultQuestion> _questionRepository;
        private readonly IBaseRepository<ConsultCategory> _categoryRepository;
        private readonly ILogger<GetConsultQuestionsHandler> _logger;
        private readonly IMapper _mapper;

        public GetConsultQuestionsHandler(
            IBaseRepository<ConsultQuestion> questionRepository,
            IBaseRepository<ConsultCategory> categoryRepository,
            ILogger<GetConsultQuestionsHandler> logger,
            IMapper mapper)
        {
            _questionRepository = questionRepository;
            _categoryRepository = categoryRepository;
            _logger = logger;
            _mapper = mapper;
        }

        public async Task<ApiResult<PagedList<ConsultQuestionDto>>> Handle(GetConsultQuestionsCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始获取健康咨询问题列表，分类ID：{CatId}，关键词：{Keyword}，页码：{PageIndex}，每页条数：{PageSize}",
                    request.CatId, request.Keyword, request.PageIndex, request.PageSize);

                // 构建基础查询
                var query = _questionRepository.GetAll().Where(q => !q.IsDeleted);

                // 按分类筛选
                if (request.CatId.HasValue)
                {
                    query = query.Where(q => q.CatId == request.CatId.Value);
                }

                // 按关键词筛选
                if (!string.IsNullOrEmpty(request.Keyword))
                {
                    query = query.Where(q => q.Title.Contains(request.Keyword) || q.Content.Contains(request.Keyword));
                }

                // 计算总数量
                var totalCount = await query.CountAsync(cancellationToken);

                // 分页并按时间倒序排序
                var questions = await query
                    .OrderByDescending(q => q.CreatedAt)
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync(cancellationToken);

                // 获取相关分类信息
                var categoryIds = questions.Select(q => q.CatId).Distinct().ToList();
                var categories = await _categoryRepository.GetAll()
                    .Where(c => !c.IsDeleted && categoryIds.Contains(c.Id))
                    .ToListAsync(cancellationToken);

                // 手动映射并添加分类名称
                var questionDtos = questions.Select(q => new ConsultQuestionDto
                {
                    Id = q.Id,
                    CatId = q.CatId,
                    CategoryName = categories.FirstOrDefault(c => c.Id == q.CatId)?.Name ?? "未知分类",
                    Title = q.Title,
                    Content = q.Content,
                    AuthorId = q.AuthorId,
                    AuthorName = "用户" + q.AuthorId, // 这里可能需要从用户表获取
                    LikeCnt = q.LikeCnt,
                    ViewCnt = q.ViewCnt,
                    Status = q.Status,
                    CreatedAt = q.CreatedAt,
                    Tags = "" // 可能需要从标签表获取
                }).ToList();

                // 构造分页结果
                var result = new PagedList<ConsultQuestionDto>
                {
                    PageIndex = request.PageIndex,
                    PageSize = request.PageSize,
                    TotalCount = totalCount,
                    TotalPages = (int)Math.Ceiling(totalCount / (double)request.PageSize),
                    Items = questionDtos
                };

                return new ApiResult<PagedList<ConsultQuestionDto>>
                {
                    Code = ApiEnum.Success,
                    Msg = "获取健康咨询问题列表成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取健康咨询问题列表时发生异常");
                return new ApiResult<PagedList<ConsultQuestionDto>>
                {
                    Code = ApiEnum.Error,
                    Msg = "获取健康咨询问题列表失败：" + ex.Message
                };
            }
        }
    }
} 